# -*- coding: iso-8859-1 -*-
import sys
from os.path import basename
from os.path import join
from os.path import abspath

def falkon_job(file_groups, global_store_path):
    tasks = "\n".join([falkon_task(file_group, global_store_path) for file_group in file_groups])
    num_execs = len(tasks)#nun_execs on falkon's idiom means the number of tasks	
    f = file('job.job', 'w')
    f.writelines(tasks)
    f.flush()
    f.close()
    return f.name

def falkon_task(input_files, global_store_path):	
    logical_input = " ".join([basename(name.strip()) for name in input_files])
    local_names = " ".join([join(global_store_path, name.strip()) for name in input_files])
    return "md5sum " + logical_input + " %%% "+ logical_input + " %%% " + local_names + \
" %%%  %%%  %%%"

""" Main Flow
Generates a Falkon job file

example:

input_file
->
1
2
3
4
<-

python vanillajob.py 2 /tmp < foo

OUTPUT -> job.job

md5sum 1 2 %%% 1 2 %%% /tmp/1 /tmp/2 %%%  %%%  %%%
md5sum 3 4 %%% 3 4 %%% /tmp/3 /tmp/4 %%%  %%%  %%%
"""

if (len(sys.argv) < 3):
    print "usage: args <num_files_per_task> <global_storage>"
    sys.exit(2)

file_names = sys.stdin.readlines()
num_files_per_task = int(sys.argv[1])
global_storage = sys.argv[2]

file_groups = []
for file_index in range(0, len(file_names), num_files_per_task):
	file_groups.append(file_names[file_index:(file_index + num_files_per_task)])

print abspath(falkon_job(file_groups, global_storage))
